<?php
/**
 * 抽奖模型
 *
 */
namespace Admin\Model;
use Think\Model;
class LotteryModel extends BaseModel{

	protected $_validate = array(
		array('name', 'require','活动名称不能为空',1),
		array('name', '1,20' ,'活动名称过长',0,'length'),
		array('start_time', '/^\d{4}-\d{1,2}-\d{1,2}$/', '开始时间格式错误', 1, '',1),
		array('start_time', 'updateTime', '开始时间必须大于当前时间', 1, 'callback', 1),
		array('end_time', '/^\d{4}-\d{1,2}-\d{1,2}$/', '结束时间格式错误', 1, 'regex',1),
		array('end_time','checkTime', '开始时间不能大于结束时间',1, 'callback', 1),
		array('start_hour', '0,24', '每日开始时间不能为空',1, 'between', 1),
		array('end_hour', '0,24', '每日结束时间不能为空', 1, 'between', 1),
		array('end_hour','checkHour', '每日开始时间不能大于等于结束时间',1, 'callback', 1),
		array('period', '1,23', '周期错误', 1, 'between', 1),
		array('type', '1,2', '签到活动类型错误',1, 'in', 1),
		array('remark', '1,200', '备注字数过多',2,'length'),
		//array('status', '0,1', '状态错误',1, 'in', 1),
		array('end_time','updateTime','结束时间必须大于当前时间',0, 'callback', 2),
		//更新时，非空就验证
		array('end_time', '/^\d{4}-\d{1,2}-\d{1,2}$/', '结束时间格式错误', 0, 'regex',2),
		array('id','require','活动id不能为空',1, '', 2)
		);
	/**
	 * 获取抽奖活动列表
	 * @param  array  $data 过滤参数
	 * @return  
	 */
	public function getList($data = array(), $pageIndex = 1)
	{
		$model = M('Lottery');
		$model->alias('l');
		//组装查询条件
		$where['l.is_deleted'] = 0;
		if (isset($data['type']) and in_array($data['type'], array(1,2))) {
			$where['l.type'] = $data['type'];
		}
		//活动名称
		if (isset($data['name']) and $data['name'] !== '') {
			$where['l.name'] = array('like', '%'.$data['name'].'%');
		}
		//活动ID
		if (isset($data['id']) and $data['id']) {
			$where['l.id'] = $data['id'];
		}
		//活动状态
		if (isset($data['status']) and $data['status'] != -1) {
			$where['l.status'] = $data['status'];
		}
		//活动创建时间开始区间
		if (isset($data['start']) and $data['start']) {
			$where['l.add_time'][] = array('egt', strtotime($data['start']));
		}
		//活动创建时间结束区间
		if (isset($data['end']) and $data['end']) {
			$where['l.add_time'][] = array('elt', strtotime($data['end'].' 23:59:59'));
		}
		if (isset($data['admin_user']) and $data['admin_user'] !== '') {
			$where['a.a_true_name'] = array('like', '%'.$data['admin_user'].'%');
			$model->join('__ADMIN__ a ON a.a_id = l.admin_id', 'LEFT');
		}
		$total = $model->where($where)->count();
		$pageSize = I('post.page_size') ?: 10;
		$page = pagination($total, $pageSize ,$pageIndex);
		if ($total) {
			$list = M('Lottery')->alias('l')->field('l.*,a.a_true_name as admin_id')
			      ->join('__ADMIN__ a ON a.a_id = l.admin_id', 'LEFT')
			      ->where($where)->order('l.id desc')
			      ->limit($page['offset'], $page['limit'])->select();
			foreach ($list as $k => $v) {
				$list[$k]['start_time'] = date('Y年m月d日', $v['start_time']);
				$list[$k]['end_time'] = date('Y年m月d日', $v['end_time']);
				$list[$k]['add_time'] = date('Y年m月d日 H:i', $v['add_time']);
				//计算已用资金
				$map['add_time'][] = array('egt', $v['start_time']);
				$map['add_time'][] = array('lt', $v['end_time']);
				$map['lottery_id'] = $v['id'];
				$used = M('LotteryRecord')->where($map)->sum('prize_amount');
				is_null($used) and $used = 0;
				$list[$k]['used'] = number_format($used, 2, '.','');
			}
			return array('data'=>$list, 'page'=>$page);
		}
		return array('data'=>array(),'page'=>$page);

	}

	/**
	 * 根据ID获取活动详情
	 * @param  int $id 活动ID
	 * @return mixed     
	 */
	public function getLotteryById($id)
	{
		$lottery = $this->find($id);
		if (!$lottery) {
			$this->setErrMsg(20001, '查找不到对应的活动');
			return false;
		}
		$prize = $this->getLotteryPrize($lottery);

		$lottery['prize'] = $prize;
		$lottery['start_time'] = date('Y-m-d', $lottery['start_time']);
		$lottery['end_time'] = date('Y-m-d', $lottery['end_time']);
		return $lottery;
	}

	public function getLotteryPrize($lottery = array())
	{
		$where['lottery_id'] = $lottery['id'];
		$where['is_deleted'] = 0;
		$default = array(array('id'=>'system','name'=>'谢谢参与','amount'=>'0.00','volume_id'=>'0','sku'=>'0','used'=>'0'));
		$prize = M('LotteryPrize')->where($where)->select();
		$prize = array_merge($default, $prize);
		//计算奖品已使用情况
		foreach ($prize as $k => $v) {
			unset($map);
			if($lottery['type'] == 1){
				if ($v['volume_id'] == 0) {
					$lottery['prize'][$k]['volume_name'] = '无';
				}else{
					$volume = M('Volume')->find($v['volume_id']);
					$prize[$k]['total'] = $volume['total'];
					$prize[$k]['volume_name'] = $volume['volume_name'];
					$prize[$k]['min'] = $volume['min'];
					$prize[$k]['start_time'] = date('Y-m-d', $volume['start_time']);
					$prize[$k]['end_time'] = date('Y-m-d', $volume['end_time']);
					$prize[$k]['category'] = $volume['category'];
					$prize[$k]['status'] = $volume['status'];
					$prize[$k]['type'] = $volume['type'] == 1 ? '代金券' : '现金券';
				}
				if($lottery['start_time'] > time()){ //活动未开始
					$prize[$k]['used'] = 0;
				}elseif($lottery['end_time'] < time()){ //活动已结束
					$end = $lottery['end_time'];
					$start = $end - 86400;
					$map['lottery_id'] = $lottery['id'];
					$map['add_time'][] = array('gt', $start);
					$map['add_time'][] = array('elt', $end);
					$map['prize_id']   = intval($v['id']);
					$count = M('LotteryRecord')->where($map)->count();
		 			$prize[$k]['used'] = $count;
				}else{ //活动进行中
					$start = strtotime(date('Y-m-d'));
					$end = $start + 86400;
					$map['lottery_id'] = $lottery['id'];
					$map['add_time'][] = array('egt', $start);
					$map['add_time'][] = array('lt', $end);
					$map['prize_id']   = intval($v['id']);
					$count = M('LotteryRecord')->where($map)->count();
		 			$prize[$k]['used'] = $count;
				}
			}else{
				if($lottery['start_time'] > time()){ //活动未开始
					$prize[$k]['used'] = 0;
				}elseif($lottery['end_time'] < time()){ //活动已结束
					//获取最后一场的奖品使用情况 
					//最后一场的结束时间,结束时间保存到59秒
		 			$end = $lottery['end_time'] - 86400 + $lottery['end_hour'] * 3600;
		 			$start = $end - $lottery['period'] * 3600;
		 			$map['lottery_id'] = $lottery['id'];
					$map['add_time'][] = array('gt', $start);
					$map['add_time'][] = array('elt', $end);
					$map['prize_id']   = intval($v['id']);
					$count = M('LotteryRecord')->where($map)->count();
		 			$prize[$k]['used'] = $count;
				}else{ //活动进行中
					//计算当场签到时间区间
		            $today = strtotime(date('Y-m-d'));
		            $signStart = $today + $lottery['start_hour'] * 3600;//签到开始时间
		            $signEnd   = $today + $lottery['end_hour'] * 3600;//签到结束时间
		            $start = $end = 0;
		            while (true) {
		                //获取下场开始时间
		                $nextStart = $signStart + $lottery['period'] * 3600;
		                if ($nextStart < time()) { //已过期，继续获取下一场
		                    $signStart = $nextStart;
		                    continue;
		                }
		                if (time() >= $signStart and time() < $nextStart) {
		                    $start = $signStart;
		                    $end = $nextStart;
		                    break;
		                }
            		}
            		$map['lottery_id'] = $lottery['id'];
					$map['add_time'][] = array('gt', $start);
					$map['add_time'][] = array('elt', $end);
					$map['prize_id']   = intval($v['id']);
					$count = M('LotteryRecord')->where($map)->count();
					$prize[$k]['used'] = $count;
				}
			}
		}
		return $prize;
	}

	/**
	 * 添加关联奖品
	 * @param int $type 1业主2师傅 
	 */
	public function checkPrize($type)
	{
		$prizes = I('post.prizes', array());
		if (!is_array($prizes) or empty($prizes)) {
			$this->setErrMsg(10001, '奖品信息错误');
			return false;
		}
		$dataList = array();
		$data = array();
		$amount = 0;
		//验证奖品数据
		foreach ($prizes as $v) {
			$data['name'] = trim($v['name']);
			$data['amount'] = $v['amount'];
			$data['volume_id'] = isset($v['volume_id']) ? intval($v['volume_id']) : 0;
			$data['sku'] = $data['surplus'] = intval($v['sku']);
			$data['add_time'] = time();
			$data['type'] = $type;
			if (empty($data['name'])) {
				$this->setErrMsg(10001, '奖品名称不能为空');
				return false;
			}
			if (mb_strlen($data['name']) > 5) {
				$this->setErrMsg(10001, '奖品名称不能超过5个字');
				return false;
			}
			if ($type == 1){
				if($data['volume_id'] < 0) {
					$this->setErrMsg(10001, '请选择电子券');
					return false;
				}
				if ($data['volume_id'] == 0) {
					$data['amount'] = 0;
				}else{
					$map['is_deleted'] = 0;
					$map['end_time'] = array('gt', time());
					$map['volume_id'] = $data['volume_id'];
					$volume = M('volume')->where($map)->find();
					if (!$volume) {
						$this->setErrMsg(10001, '电子券添加错误');
						return false;
					}else{
						$data['amount'] = $volume['total'];
					}
				}
			}else{
				if (!is_numeric($data['amount']) or $data['amount'] < 0) {
					$this->setErrMsg(10001, '奖品金额错误');
					return false;
				}
			}
			if ($data['sku'] < 0) {
				$this->setErrMsg(10001,'库存设置错误');
				return false;
			}
			$amount += $data['amount'] * $data['sku'];
			$dataList[] = $data;
		}
		if (count($dataList) != 7) {
			$this->setErrMsg(10001, '动态奖品必须设置7个');
			return false;
		}
		return array('prize'=>$dataList, 'amount'=>$amount);
	}	

	/**
	 * 日志
	 * @param  array $data 查询条件
	 * @param bool $down 是否下载
	 * @return [type]       [description]
	 */
	public function getLogList($data, $down = false)
	{
		$model = M('LotteryRecord');
		$model->alias('r');
		$map['r.is_deleted'] = 0;
		//组装查询条件
		//活动创建时间开始区间
		if (isset($data['start']) and $data['start']) {
			$map['r.add_time'][] = array('egt', strtotime($data['start'].' 00:00:00'));
		}
		//活动创建时间结束区间
		if (isset($data['end']) and $data['end']) {
			$map['r.add_time'][] = array('elt', strtotime($data['end'].' 23:59:59'));
		}
		if (isset($data['user_id']) and $data['user_id'] !== '') {
			$map['r.user_id'] = array('LIKE', '%'.$data['user_id'].'%');
		}
		if (isset($data['rec_id']) and $data['rec_id'] !== '') {
			$map['r.id'] = array('LIKE','%'.$data['rec_id'].'%');
		}
		if (isset($data['lottery_id']) and $data['lottery_id'] !== '') {
			$map['r.lottery_id'] = array('LIKE', '%'.$data['lottery_id'].'%');
		}
		if (isset($data['type']) and in_array($data['type'], array(1,2))) {
			$map['r.role'] = $data['type'];
		}
		if (isset($data['name']) and $data['name'] !== '') {
			$model->join('__LOTTERY__ l ON l.id = r.lottery_id', 'LEFT');
			$map['l.name'] = array('like', '%'.$data['name'].'%');
		}
		if (isset($data['user_name']) and $data['user_name'] !== '') {
			$model->join('__USER__ u ON u.user_id = r.user_id', 'LEFT');
			$map['u.user_name'] = array('like', '%'.$data['user_name'].'%');
		}
		$total = $model->where($map)->count();
		$pageSize = isset($data['page_size']) ? $data['page_size'] : 10;
		$pageIndex = isset($data['page']) ? $data['page'] : 1;
		$pageSize < 0 and $pageSize = 10;
		$pageIndex < 0 and $pageIndex = 1;
		
		$page = pagination($total, $pageSize ,$pageIndex);
		if ($total) {
			 $list = $model->field('r.*,l.name,u.user_name')->alias('r')
			 ->join('__USER__ u ON u.user_id = r.user_id', 'LEFT')
			 ->join('__LOTTERY__ l ON l.id = r.lottery_id', 'LEFT')
			 ->where($map)->order('r.id desc');
			 if ($down) {
			 	$list = $list->select();
			 }else{
			 	$list = $list->limit($page['offset'], $page['limit'])->select();
			 }
			foreach ($list as $k => $v) {
				$list[$k]['add_time'] = date('Y年m月d日 H:i', $v['add_time']);
			}
			return array('data'=>$list, 'page'=>$page);
		}
		return array('data'=>array(),'page'=>$page);
	
	}

	public function getStastics($data)
	{
		$model = M('LotteryRecord');
		$where = ' WHERE r.is_deleted = 0';
		//活动创建时间开始区间
		if (isset($data['start']) and $data['start']) {
			$where .= ' AND r.add_time >= '.strtotime($data['start'].' 00:00:00');
		}
		//活动创建时间结束区间
		if (isset($data['end']) and $data['end']) {
			$where .= ' AND r.add_time <= '.strtotime($data['end'].' 23:59:59');
		}
		if (isset($data['lottery_id']) and $data['lottery_id'] > 0) {
			$where .= ' AND r.lottery_id = '.$data['lottery_id'];
		}
		if (isset($data['type']) and in_array($data['type'], array(1,2))) {
			$where .= ' AND r.role = '.$data['type'];
		}
		if (isset($data['name']) and $data['name'] !== '') {
			$where .= ' AND l.name LIKE "%'.$data['name'].'%"';
			$join = 'LEFT JOIN __LOTTERY__ l ON l.id = r.lottery_id';
		}else{
			$join = '';
		}
		//是否按活动统计
		if ($data['group']) {
			$sql = 'SELECT l.id,l.name,SUM(1) as count,SUM(prize_amount) as amount '.
			       'FROM __LOTTERY_RECORD__ r LEFT JOIN __LOTTERY__ l ON l.id = r.lottery_id'.
			       $where.' GROUP BY l.id ORDER BY l.id DESC ';
			$res = M()->query($sql);
			if ($res) {
				$total = count($res);
				$pageSize = isset($data['page_size']) ? $data['page_size'] : 10;
				$page = pagination($total, $pageSize ,$data['page']);
				$newData = array();
				foreach ($res as $k => $v) {
					if ($k >= $page['offset'] and count($newData) < $page['limit']) {
						$newData[] = $v;
					}
				}
				return array('data'=>$newData,'page'=>$page);
			}else{
				return array('data'=>array(),'page'=>array());
			}
		}else{
			$sql = 'SELECT SUM(1) as count,SUM(prize_amount) as amount '.
			       'FROM __LOTTERY_RECORD__ r '.$join.$where;
			$res = M()->query($sql);
			if ($res) {
				$data = $res[0];
				is_null($data['count']) and $data['count'] = 0;
				is_null($data['amount']) and $data['amount'] = 0.00;
				return array('data'=>$data,'page'=>array());
			}else{
				return array('data'=>array(),'page'=>array());
			}
		}
	}

	//检查是否可以改变状态
	public function canChangeStatus($id, $status)
	{
		$lottery = $this->find($id);
		if (!$lottery) {
			$this->setErrMsg(20001, '查找不到对应的活动');
			return false;
		}
		// if ($status == 1) {
		// 	// $where['start_time'] = array('between', array($lottery['start_time'],$lottery['end_time']));
		// 	// $where['end_time'] = array('between', array($lottery['start_time'],$lottery['end_time']));
		// 	// $where['_logic'] = 'or';
		// 	// $map['status']   = 1;
		// 	// $map['type'] = $lottery['type'];
		// 	// $map['id'] = array('neq', $id);
		// 	// $map['_complex'] = $where;
		// 	$map['type'] = $lottery['type'];
		// 	$map['status'] = 1;
		// 	$isExist = $this->where($map)->count();
		// 	if($isExist){
		// 		$this->setErrMsg(20001, '同一时间只能存在一个上线的活动');
		// 		//$this->setErrMsg(20001, '该活动上线时间与“'.$isExist['name'].'”上线时间冲突');
		// 		return false;
		// 	}
		//}
		return $lottery;
	}

	//清除缓存 
	public function clearCache($id){
		$lottery = $this->find($id);
		if ($lottery) {
	        //是否需要更新缓存
	        $cacheKey = '_LOTTERY_'.$lottery['type'].'_';
	        $prizeKey = '_LOTTERY_PRIZE_'.$lottery['type'].'_';
	        S(array('type'=>'redis'));
	        S($cacheKey, null);
	        S($prizeKey, null);
		}
        // if ($cache = S($cacheKey) and $cache['id'] == $lottery['id']) {
        //     if($lottery['status'] == 0){//活动下线，清除缓存
        //     	S($cacheKey, null);
        //     	S($prizeKey, null);
        //     }else{//活动上线，更新时间
        //     	//活动缓存
        //     	S($cacheKey, $lottery, array('type'=>'redis','expire'=>$lottery['end_time']-time()));
        //     	//奖品缓存
        //     	if($prize = S($prizeKey)){
        //     		S($prizeKey, $prize, array('type'=>'redis','expire'=>$lottery['end_time']-time()));
        //     	}

        //     }
        // }
	}

	/**
	 * 验证时间规则 
	 * @return [type] [description]
	 */
	public function checkTime()
	{
		if(strtotime($_POST['start_time']) <= strtotime($_POST['end_time'])){
    		return true;
  		}
  		return false;
	}
	/**
	 * 验证时间规则
	 * @return [type] [description]
	 */
	public function checkHour()
	{
		if ($_POST['type'] == 2){
			if ($_POST['start_hour'] < $_POST['end_hour']) {
				return true;
			}
			return false;
		}
		return true;
	}

	public function updateTime($time)
	{
		if (strtotime($time) > time()) {
			return true;
		}
		return false;
	}
}
?>